import { readUriToTextAndExplode } from "../readFileToText/openTextFile";
import { Coordinate } from "../coordParser/Coordinate";
import { IEseSidStar } from "../interfaces/IEseSidStar";
import { RenderData } from "../classes/RadarRenderData";

export async function loadEseFile(uri: string) {
    const lines = await readUriToTextAndExplode(uri, ';');
    let asFlag = false;//空域读取
    let ftFlag = false;//字读取
    let poFlag = false;//位置读取
    let ssFlag = false;//程序读取
    let activeSectorName = '';//正在处理的Sector
    const airspaceSectorLineEntryRegex = new RegExp('SECTORLINE:(?<name>.*)');
    // const airspaceCircleSectorLineFirstEntryRegex = new RegExp('CIRCLE_SECTORLINE:(?<name>[^:]*):(?<center>[^:]*):(?<radius>\\S*)');
    // const airspaceCircleSectorLineSecondEntryRegex = new RegExp('CIRCLE_SECTORLINE:(?<name>[^:]*):(?<coord1>[NSEW]\\d+.\\d+.\\d+.\\d+):(?<coord2>[NSEW]\\d+.\\d+.\\d+.\\d+):(?<radius>\\S*)');
    const airspaceCoordAppendRegex = new RegExp('COORD:(?<coord1>[NSEW]\\d+.\\d+.\\d+.\\d+):(?<coord2>[NSEW]\\d+.\\d+.\\d+.\\d+)');
    const airspaceDisplayRegex = new RegExp('DISPLAY:(?<my>[^:]*):(?<o1>[^:]*):(?<o2>[^:]*)');
    const airspaceOwnerRegex = new RegExp('OWNER:(?<owners>.*)');
    const airspaceSectorEntryRegex = new RegExp('SECTOR:(?<name>[^:]*):(?<loAlt>\\d*):(?<hiAlt>\\d*)');
    const airspaceBorderRegex = new RegExp('BORDER:(?<borders>.*)');
    const freetextRegex = new RegExp('(?<coord1>[NSEW]\\d+.\\d+.\\d+.\\d+):(?<coord2>[NSEW]\\d+.\\d+.\\d+.\\d+)(:(?<group>[^:]*))?:(?<text>.*)')
    const positionRegex = new RegExp('(?<name>[^:]*):(?<radio>[^:]*):(?<freq>[^:]*):(?<ident>[^:]*):(?<ml>[^:]*):(?<prefix>[^:]*):(?<suffix>[^:]*):[^:]*:[^:]*:(?<csr>[^:]*):(?<cer>[^:]*):?(?<visCenters>.*)');
    const sidStarRegex = new RegExp('(?<type>SID|STAR):(?<airport>[^:]*):(?<runway>[^:]*):(?<name>[^:]*):(?<route>.*)')
    const resetFlag = () => {
        asFlag = false;
        ftFlag = false;
        poFlag = false;
        ssFlag = false;
    }
    for (let line of lines) {
        const tag = line.toUpperCase();
        if (tag == '[AIRSPACE]') {
            resetFlag();
            asFlag = true;
            continue;
        } else if (tag == '[FREETEXT]') {
            resetFlag();
            ftFlag = true;
            continue;
        } else if (tag == '[POSITIONS]') {
            resetFlag();
            poFlag = true;
            continue;
        } else if (tag == '[SIDSSTARS]') {
            resetFlag();
            ssFlag = true;
            continue;
        }
        if (poFlag && positionRegex.test(line)) {
            const match = positionRegex.exec(line);
            if (match != null && match.groups != undefined) {
                const g = match.groups;
                const visCenters = g.visCenters;
                let vc: Coordinate[] = [];
                if (visCenters != undefined) {
                    const vsArray = visCenters.split(':');
                    for (let i = 0; i < vsArray.length - 1; i += 2) {
                        const c = new Coordinate();
                        vc.push(c.setFromStr(vsArray[i]).setFromStr(vsArray[i + 1]));
                    }
                }
                RenderData.ese.position.push({
                    name: g.name,
                    callsign: g.radio,
                    frequency: g.freq,
                    identifier: g.ident,
                    middleLetter: g.ml,
                    prefix: g.prefix,
                    suffix: g.suffix,
                    startOfRange: g.csr,
                    endOfRange: g.cer,
                    visCenter: vc
                });
            }
        } else if (ftFlag && freetextRegex.test(line)) {
            const match = freetextRegex.exec(line);
            if (match != null && match.groups != undefined) {
                const g = match.groups;
                RenderData.ese.freetext.push({
                    group: g.group,
                    text: g.text,
                    coord: new Coordinate().setFromStr(g.coord1).setFromStr(g.coord2)
                })
            }
        } else if (ssFlag && sidStarRegex.test(line)) {
            const match = sidStarRegex.exec(line);
            if (match != null && match.groups != undefined) {
                const g = match.groups;
                const target: IEseSidStar = {
                    name: g.name,
                    runway: g.runway,
                    airport: g.airport,
                    route: g.route.split(' ')
                };
                if (g.type.toUpperCase() == 'SID') {
                    RenderData.ese.sid.push(target);
                } else if (g.type.toUpperCase() == 'STAR') {
                    RenderData.ese.star.push(target);
                }
            }
        } else if (asFlag) {
            const i = RenderData.ese.airspace.findIndex(a => a.name == activeSectorName);
            if (airspaceSectorLineEntryRegex.test(line)) {
                const match = airspaceSectorLineEntryRegex.exec(line);
                if (match != null && match.groups != undefined) {
                    const g = match.groups;
                    activeSectorName = g.name;
                    RenderData.ese.airspace.push({
                        name: g.name,
                        activeCondition: null,
                        coords: [],
                        displayCondition: [],
                        subsection: []
                    });
                }
            } else if (airspaceCoordAppendRegex.test(line)) {
                const match = airspaceCoordAppendRegex.exec(line);
                if (match != null && match.groups != undefined) {
                    const g = match.groups;
                    if (i != -1) {
                        RenderData.ese.airspace[i].coords.push(new Coordinate().setFromStr(g.coord1).setFromStr(g.coord2));
                    }
                }
            } else if (airspaceDisplayRegex.test(line)) {
                const match = airspaceDisplayRegex.exec(line);
                if (match != null && match.groups != undefined) {
                    const g = match.groups;
                    if (i != -1) {
                        RenderData.ese.airspace[i].displayCondition.push({
                            sectorControlling: g.my,
                            sectorCovered: [g.o1, g.o2]
                        });
                    }
                }
            } else if (airspaceOwnerRegex.test(line)) {
                const match = airspaceOwnerRegex.exec(line);
                if (match != null && match.groups != undefined) {
                    const g = match.groups;
                    if (i != -1) {
                        const subIndex = RenderData.ese.airspace[i].subsection.findIndex(s => s.sector.name == activeSectorName);
                        if (subIndex != -1) {
                            RenderData.ese.airspace[i].subsection[subIndex].owner = g.owners.split(':');
                        }
                    }
                }
            } else if (airspaceSectorEntryRegex.test(line)) {
                const match = airspaceSectorEntryRegex.exec(line);
                if (match != null && match.groups != undefined) {
                    const g = match.groups;
                    activeSectorName = g.name;
                    const i = RenderData.ese.airspace.findIndex(a => a.name == activeSectorName);
                    if (i != -1) {
                        RenderData.ese.airspace[i].subsection.push({
                            sector: {
                                name: g.name,
                                loAltLimit: Number(g.loAlt),
                                upAltLimit: Number(g.hiAlt)
                            },
                            owner: [],
                            altOwner: [],
                            border: []
                        });
                    }
                }
            } else if (airspaceBorderRegex.test(line)) {
                const match = airspaceBorderRegex.exec(line);
                if (match != null && match.groups != undefined) {
                    const g = match.groups;
                    if (i != -1) {
                        const subIndex = RenderData.ese.airspace[i].subsection.findIndex(s => s.sector.name == activeSectorName);
                        if (subIndex != -1) {
                            RenderData.ese.airspace[i].subsection[subIndex].border = g.borders.split(':');
                        }
                    }
                }
            }
        }
    }
    console.log('ese data', RenderData.ese);
}